package com.stationbuilding.fragment.quality;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;
import com.stationbuilding.R;
import com.stationbuilding.adapter.TimeSpinnerAdapter;
import com.stationbuilding.api.RetrofitManager;
import com.stationbuilding.bean.CountBean;
import com.stationbuilding.bean.CountListBean;
import com.stationbuilding.bean.DictBean;
import com.stationbuilding.bean.DictListBean;
import com.stationbuilding.constants.Constants;
import com.stationbuilding.utils.PreferenceHelper;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import lecho.lib.hellocharts.listener.PieChartOnValueSelectListener;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.PieChartView;

public class QualityFragmentStatus extends Fragment {

    private View view;
    private Spinner spinner;
    private TimeSpinnerAdapter spinnerAdapter;
    private String timeId;
    private List<DictBean> timeList = new ArrayList<>();
    private ProgressDialog dialog;//加载提示
    private PieChartView pieChart;
    private String token = PreferenceHelper.getInstance(getActivity()).getToken();
    private Spinner.OnItemSelectedListener spinnerItemSelectedListener = new Spinner.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            timeId = timeList.get(position).getId();
            setPieChartData();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_quality_status, container, false);
        init();
        return view;
    }

    private void init() {
        // 时间选择框
        spinner = (Spinner) view.findViewById(R.id.time_spinner);
        spinnerAdapter = new TimeSpinnerAdapter(getActivity(), R.layout.statistic_spinner_item, timeList);
        spinnerAdapter.setDropDownResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(spinnerItemSelectedListener);
        loadTimeList();

        // 图表
        pieChart = (PieChartView) view.findViewById(R.id.chart);
    }

    /**
     * 数据加载
     */
    private void loadTimeList() {
        RetrofitManager.toSubscribe(
                RetrofitManager.getApiService().getDictListByPid(token, Constants.DICT_ID_STATISTIC_DATE),
                new Observer<DictListBean>() {

            @Override
            public void onComplete() {
                spinner.setSelection(0);
            }

            @Override
            public void onError(Throwable e) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                Toast.makeText(getActivity(), "网络连接失败，请重新加载", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSubscribe(@NonNull Disposable d) {
                if (dialog == null || !dialog.isShowing()) {
                    dialog = ProgressDialog.show(getActivity(), null, "加载数据...");
                }
            }

            @Override
            public void onNext(DictListBean dictListBean) {
                timeList = dictListBean.getDictList();
                spinnerAdapter.setTimeList(timeList);
                spinnerAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 设置图表数据
     */
    private void setPieChartData() {
        RetrofitManager.toSubscribe(
                RetrofitManager.getApiService().getCountByStatus(token, Constants.QUESTION_TYPE_QUALITY, timeId),
                new Observer<CountListBean>() {

            @Override
            public void onComplete() {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable e) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                Toast.makeText(getActivity(), "出错", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSubscribe(@NonNull Disposable d) {
                if (dialog == null || !dialog.isShowing()) {
                    dialog = ProgressDialog.show(getActivity(), null, "加载数据...");
                }
            }

            @Override
            public void onNext(CountListBean countListBean) {
                List<SliceValue> values = new ArrayList<>();
                List<CountBean> countList = countListBean.getCountList();
                if (countList == null || countList.size() == 0) {
                    return;
                }
                for (CountBean countBean : countList) {
                    SliceValue sliceValue = new SliceValue((float) countBean.getCount(), ChartUtils.pickColor());
                    sliceValue.setLabel(countBean.getProcessStatusName() + ":" + countBean.getCount());
                    values.add(sliceValue);
                }

                final PieChartData pieChartdata = new PieChartData();
                //显示标签信息
                pieChartdata.setHasLabels(true);
                //true：只有点击对应的模块才显示标签信息  false：全部展示出来
                pieChartdata.setHasLabelsOnlyForSelected(false);
                //true：占的百分比否显示在饼图外面 false：显示在模块的中间
                pieChartdata.setHasLabelsOutside(false);
                //true：环形显示 false：圆形显示
                pieChartdata.setHasCenterCircle(true);
                //设置每个模板之间的间隙
                pieChartdata.setSlicesSpacing(1);
                //只有设置样式为圆环才能有效设置文字 （在assets目录下新建fonts目录，把ttf字体文件放到这）
                //Typeface tf = Typeface.createFromAsset(getAssets(), "你的字体资源文件路径");
                //pieChartdata.setCenterText1Typeface(tf);
                //填充数据 注意不能放在最后 否则就只显示条
                pieChartdata.setValues(values);

                //设置中间环形的颜色 只有setHasCenterCircle(true)为环形时配合使用 这里我的模式为圆形故不用
                pieChartdata.setCenterCircleColor(Color.WHITE);
                //设置环形的大小级别 也是配合setHasCenterCircle(true)使用
                pieChartdata.setCenterCircleScale(0.5f);

                //将参数设置到控件上
                pieChart.setPieChartData(pieChartdata);
                //true：点击选中模块变大  false：只有手指按住模板时才变大，手指离开恢复原状
                pieChart.setValueSelectionEnabled(true);
                pieChart.setAlpha(1f);//设置透明度
                //设置饼图大小 值越大图越大 1是与父控件相等（如果设置便签信息在饼图外面建议设置0.9f 否则会出现展示不全）
                pieChart.setCircleFillRatio(0.9f);

                //点击事件 (只有设置样式为圆环才能有效)
                pieChart.setOnValueTouchListener(new PieChartOnValueSelectListener() {
                    @Override
                    public void onValueSelected(int i, SliceValue sliceValue) {
                    }

                    @Override
                    public void onValueDeselected() {
                    }
                });
            }
        });
    }
}
